package com.fancyy.scm.util;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * Created by curry on 2017/8/23.
 */

public class PopWindowUtil {

    /**
     * 从控件下面弹出
     *
     * @param view
     */
    public static PopupWindow showAsDropDown(int layoutID, Activity mActivity, View view) {
        View popupView = mActivity.getLayoutInflater().inflate(layoutID, null);
        PopupWindow mPopupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        setWindowAlpha(mActivity, 0.5f);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity.getResources(), (Bitmap) null));
        mPopupWindow.showAsDropDown(view);
        mPopupWindow.setOnDismissListener(() -> setWindowAlpha(mActivity, 1f));

        return mPopupWindow;
    }

    /**
     * 设置半透明效果
     *
     * @param alpha
     */
    public static void setWindowAlpha(Activity mActivity, float alpha) {
        if (alpha < 0 || alpha > 1) return;
        WindowManager.LayoutParams windowLP = mActivity.getWindow().getAttributes();
        windowLP.alpha = alpha;
        if (alpha == 1) {
            mActivity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
        } else {
            mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);//此行代码主要是解决在华为手机上半透明效果无效的bug
        }
        mActivity.getWindow().setAttributes(windowLP);
    }
}
